package com.yunqiao.service.api.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yunqiao.common.consts.AppConsts;
import com.yunqiao.common.exception.CustomApiException;
import com.yunqiao.common.exception.DbTransactionException;
import com.yunqiao.common.validator.Assert;
import com.yunqiao.service.api.AppAccountService;
import com.yunqiao.service.api.entity.ApplyDriverEntity;
import com.yunqiao.service.api.entity.RedPacketEntity;
import com.yunqiao.service.api.entity.UserEntity;
import com.yunqiao.service.api.form.ForgetPasswordForm;
import com.yunqiao.service.api.form.LoginForm;
import com.yunqiao.service.api.form.RegisterForm;
import com.yunqiao.service.api.mapper.ApplyDriverMapper;
import com.yunqiao.service.api.mapper.RedPacketMapper;
import com.yunqiao.service.api.mapper.SysSmscodeMapper;
import com.yunqiao.service.api.mapper.UserMapper;
import com.yunqiao.service.api.util.AccountEnum;
import com.yunqiao.service.sys.SysUserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * @program: server
 * @description:
 * @author: Crocutax
 * @company: 今日速运
 * @e-mail: wangxw725@163.com
 * @create: 2019-03-04 14:27
 **/
@Service
public class AppAccountServiceImpl implements AppAccountService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedPacketMapper redPacketMapper;
    @Autowired
    private SysSmscodeMapper sysSmscodeMapper;
    @Autowired
    private SysUserService sysSmscodeService;
    @Autowired
    private ApplyDriverMapper applyDriverMapper;

    @Override
    @Transactional(rollbackFor = DbTransactionException.class)
    public Long register(RegisterForm form) {
        //todo 这里逻辑有问题
        //检查验证码
        sysSmscodeService.checkedSmsCode(form.getPhone(), form.getSmsCode());
        //数据查重
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<UserEntity>().eq("account", form.getPhone()).eq("role_type",form.getRoleType());
        UserEntity dbUserEntity = userMapper.selectOne(queryWrapper);
        if (dbUserEntity != null) {
            if(dbUserEntity.getRoleType().equals(AppConsts.USER_ROLE_TYPE_1)){
                throw new CustomApiException("该手机号已注册用户端,请在用户端直接登陆");
            }else {
                throw new CustomApiException("该手机号已注册司机端,请在司机端直接登陆");
            }
        }

        UserEntity user = new UserEntity();
        user.setPhone(form.getPhone());
        user.setAccount(form.getPhone());
        //注册司机也先生成用户，等待后台审核
        user.setSuperiorUserId(form.getSuperiorUserId());
        user.setPassword(DigestUtils.sha256Hex(form.getPassword()));
        user.setRoleType(form.getRoleType());
        user.setQqOpenid(form.getQqOpenid());
        user.setWxOpenid(form.getWxOpenid());
//        if (user.getRoleType().equals(AppConsts.USER_ROLE_TYPE_2)) {
//            user.setApplyDriver(AppConsts.USER_APPLY_DRIVER_1);
//        }
        userMapper.insert(user);

//        if (user.getRoleType().equals(AppConsts.USER_ROLE_TYPE_2)) {
//            //创建成为司机审核
//            ApplyDriverEntity applyDriverEntity = new ApplyDriverEntity();
//            applyDriverEntity.setStatus(AppConsts.USER_APPLY_DRIVER_1);
//            applyDriverEntity.setPhone(form.getPhone());
//            applyDriverEntity.setUserId(user.getId());
//            applyDriverMapper.insert(applyDriverEntity);
//        }

        // 如果有上级ID,则给自己发个10元红包
        if (form.getSuperiorUserId() != null) {
            RedPacketEntity packetEntity = new RedPacketEntity();
            packetEntity.setAmount(new BigDecimal(10));
            packetEntity.setUserId(user.getId());
            redPacketMapper.insert(packetEntity);
        }
        return user.getId();
    }

    @Override
    public UserEntity login(LoginForm form) {
        UserEntity user = userMapper.selectOne(new QueryWrapper<UserEntity>().eq("account", form.getAccount()).eq("role_type",form.getRoleType()));
        Assert.isNull(user, "该账号未注册");
        if (user.getDeleted().equals(1)) {
            throw new CustomApiException("此账号已被冻结");
        }
        if (form.getType() == AccountEnum.LoginType.PASSWORD.getValue()) {
            //密码错误
            if (!user.getPassword().equals(DigestUtils.sha256Hex(form.getPassword()))) {
                throw new CustomApiException("密码错误");
            }
        } else {
            //校验验证码
            //获取最近的一条数据
            sysSmscodeService.checkedSmsCode(form.getAccount(), form.getSmsCode());
        }

        if (!user.getRoleType().equals(form.getRoleType())) {
            if (form.getRoleType().equals(AppConsts.USER_ROLE_TYPE_1)) {
                throw new CustomApiException("请到司机端登录");
            } else if (form.getRoleType().equals(AppConsts.USER_ROLE_TYPE_2)) {
                throw new CustomApiException("请到用户端登录");

            }
        }
        return user;
    }

    @Override
    public void forgerPassword(ForgetPasswordForm form) {
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<UserEntity>()
            .eq("phone", form.getPhone())
            .eq("role_type", form.getRoleType());
        UserEntity user = userMapper.selectOne(queryWrapper);
        Assert.isNull(user, "该手机号未注册");
        sysSmscodeService.checkedSmsCode(form.getPhone(), form.getSmscode());
        user.setPassword(DigestUtils.sha256Hex(form.getNewPassword()));
        userMapper.updateById(user);
    }

    /**
     * 验证短信
     * @param phone        手机号码
     * @param inputSmscode
     */
    /*public void checkSmscode(String phone, String inputSmscode) {
        QueryWrapper<SmscodeEntity> smscodeEntityQueryWrapper = new QueryWrapper<SmscodeEntity>().eq("phone", phone);
        SmscodeEntity smscodeEntity = smscodeMapper.selectOne(smscodeEntityQueryWrapper);
        if (smscodeEntity == null
            || StrUtil.equals(smscodeEntity.getSmscode(), inputSmscode)
            || (DateUtil.between(smscodeEntity.getCreateTime(), new Date(), DateUnit.MINUTE) > SmscodeEntity.VALID_TIME)) {
            throw new CustomApiException("无效的验证码");
        }
        //用完删除
        smscodeMapper.deleteById(smscodeEntity.getId());
    }*/
}
